package cn.tedu.csmall.server.repo.impl;

import cn.tedu.csmall.server.pojo.vo.BrandDetailVO;
import cn.tedu.csmall.server.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.server.repo.IBrandRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lixin
 * @Date 2022/8/26
 */
@Repository
public class BrandRepositoryImpl implements IBrandRepository {
    public BrandRepositoryImpl() {
        System.out.println("BrandRepositoryImpl.BrandRepositoryImpl");
    }

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void put(BrandDetailVO brandDetailVO) {
        String key = KEY_PREFIX_BRAND_ITEM + brandDetailVO.getId();
        ValueOperations<String, Serializable> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, brandDetailVO);
    }

    @Override
    public BrandDetailVO get(Long id) {
        String key = KEY_PREFIX_BRAND_ITEM + id;
        Serializable serializable = redisTemplate.opsForValue().get(key);
        BrandDetailVO brand = null;
        if (serializable instanceof BrandDetailVO) {
            brand = (BrandDetailVO) serializable;
        }
        return brand;
    }

    @Override
    public void putList(List<BrandListItemVO> list) {
        ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
        for (BrandListItemVO brandDetailVO : list) {
            opsForList.rightPush(KEY_PREFIX_BRAND_LIST, brandDetailVO);
        }
    }

    @Override
    public List<BrandListItemVO> getList() {
        ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
        List<Serializable> range = opsForList.range(KEY_PREFIX_BRAND_LIST, 0, -1);
        ArrayList<BrandListItemVO> brandDetailVOS = new ArrayList<>();
        for (Serializable serializable : range) {
            if (serializable instanceof BrandListItemVO) {
                BrandListItemVO brand = (BrandListItemVO) serializable;
                brandDetailVOS.add(brand);
            }

        }
        return brandDetailVOS;
    }

    @Override
    public void deleteList() {
        String key = KEY_PREFIX_BRAND_LIST;
        redisTemplate.delete(key);
    }

    @Override
    public void deleteItem(Long id) {
        String key = KEY_PREFIX_BRAND_LIST + id;
        redisTemplate.delete(key);
    }
}
